﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeCamp12.Domain;
using System.Data.SqlClient;
using System.Configuration;
using log4net;

namespace CodeCamp12.Domain
{
    
   public class EventDataManagament
    {
       private ConnectionStringProvider connString = new ConnectionStringProvider();
       private ILog log = LogManager.GetLogger("CodeCamp12.DAL");

       /// <summary>
       /// Returns the location for the current event
       /// </summary>
       /// <returns>Event</returns>
       public Event GetLocationForCurrentEvent()
       {
           var currentEvent= new Event();
           var events = GetAllEvents();
           foreach (Event testEvent in events)
           {
              if(testEvent.Active == 1)
               {
                   currentEvent = testEvent;
               }
           }
           return currentEvent;
       }

       /// <summary>
       /// Returns all the events in the database
       /// </summary>
       /// <returns></returns>
       public List<Event> GetAllEvents()
       {
           var eventList = new List<Event>();
           var conn = connString.GetConnection();
           var comm = new SqlCommand("GetAllEvents", conn) {CommandType = System.Data.CommandType.StoredProcedure};
           try
           {
               
               conn.Open();
               var reader = comm.ExecuteReader();
               while (reader.Read())
               {
                   var eventNew = new Event
                                      {
                                          EventID = new Guid(reader["EventID"].ToString()),
                                          EventName = reader["EventName"].ToString(),
                                          StartingFrom = Convert.ToDateTime(reader["StartingFrom"].ToString()),
                                          EndingAt = Convert.ToDateTime(reader["EndingAt"].ToString()),
                                          Location = reader["Location"].ToString(),
                                          Latitude = Convert.ToDouble(reader["Latitude"]),
                                          Longitude = Convert.ToDouble(reader["Longitude"]),
                                          Active = Convert.ToInt32(reader["Active"]),
                                          Finished = Convert.ToInt32(reader["Finished"])
                                      };
                   eventList.Add(eventNew);
               }
               reader.Close();

           }
           catch(Exception ex)
           {
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }
           return eventList;
       }

       /// <summary>
       /// Returns the event with Id passed as parametar
       /// </summary>
       /// <param name="eventId"></param>
       /// <returns>Event</returns>
       public Event GetEventById(Guid eventId)
       {
           var newEvent = new Event();
           var conn = connString.GetConnection();
           var comm = new SqlCommand("GetEventById", conn) { CommandType = System.Data.CommandType.StoredProcedure };
           comm.Parameters.AddWithValue("@id", eventId);
           try
           {
               conn.Open();
               var reader = comm.ExecuteReader();
               if(reader.Read())
               {
                   newEvent.EventID = new Guid(reader["EventID"].ToString());
                   newEvent.EventName = reader["EventName"].ToString();
                   newEvent.StartingFrom = Convert.ToDateTime(reader["StartingFrom"].ToString());
                   newEvent.EndingAt = Convert.ToDateTime(reader["EndingAt"].ToString());
                   newEvent.Location = reader["Location"].ToString();
                   newEvent.Latitude = Convert.ToDouble(reader["Latitude"].ToString()); ;
                   newEvent.Longitude = Convert.ToDouble(reader["Longitude"].ToString());
               }
               reader.Close();
           }
           catch (Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }

           return newEvent;
       }

       /// <summary>
       /// Returns the current Code Camp event
       /// </summary>
       /// <returns></returns>
       public Event GetCurrentEvent()
       {
           var newEvent = new Event();
           var conn = connString.GetConnection();
           var comm = new SqlCommand("GetCurrentEvent", conn) { CommandType = System.Data.CommandType.StoredProcedure };
         
           try
           {
               conn.Open();
               var reader = comm.ExecuteReader();
               if (reader.Read())
               {
                   newEvent.EventID = new Guid(reader["EventID"].ToString());
                   newEvent.EventName = reader["EventName"].ToString();
                   newEvent.StartingFrom = Convert.ToDateTime(reader["StartingFrom"].ToString());
                   newEvent.EndingAt = Convert.ToDateTime(reader["EndingAt"].ToString());
                   newEvent.Location = reader["Location"].ToString();
                   newEvent.Latitude = Convert.ToDouble(reader["Latitude"].ToString()); ;
                   newEvent.Longitude = Convert.ToDouble(reader["Longitude"].ToString());
                   newEvent.Finished = Convert.ToInt32(reader["Finished"]);
               }
               reader.Close();
           }
           catch (Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }

           return newEvent;
       }
       
       /// <summary>
       /// Sets the finished parametar to true
       /// </summary>
       /// <param name="eventId"></param>
       public void SetEventToFinished(Guid eventId)
       {
           var conn = connString.GetConnection();
           var comm = new SqlCommand("MakeFinished", conn) { CommandType = System.Data.CommandType.StoredProcedure };
           comm.Parameters.AddWithValue("@id", eventId);
           try
           {
               conn.Open();
               comm.ExecuteNonQuery();
           }
           catch (Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }
        
       }

       /// <summary>
       /// Updates existing event in the database
       /// </summary>
       /// <param name="eventNew"></param>
       public void UpdateEvent(Event eventNew)
       {
           var conn = connString.GetConnection();
           var comm = new SqlCommand("UpdateEvent", conn) {CommandType = System.Data.CommandType.StoredProcedure};
           comm.Parameters.AddWithValue("@EventID", eventNew.EventID);
           comm.Parameters.AddWithValue("@EventName", eventNew.EventName);
           comm.Parameters.AddWithValue("@StartingFrom", eventNew.StartingFrom);
           comm.Parameters.AddWithValue("@EndingAt", eventNew.EndingAt);
           comm.Parameters.AddWithValue("@Location", eventNew.Location);
           comm.Parameters.AddWithValue("@Latitude", eventNew.Latitude.ToString());
           comm.Parameters.AddWithValue("@Longitude", eventNew.Longitude.ToString());
           try
           {
               conn.Open();
               comm.ExecuteNonQuery();
           }
           catch(Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }
       }

       /// <summary>
       /// Deletes event from the database
       /// </summary>
       /// <param name="eventNew"></param>
       public void DeleteEvent(Event eventNew)
       {
           var conn = connString.GetConnection();
           var comm = new SqlCommand("DeleteEvent", conn) {CommandType = System.Data.CommandType.StoredProcedure};
           comm.Parameters.AddWithValue("@EventID", eventNew.EventID);
           try
           {
               conn.Open();
               comm.ExecuteNonQuery();
           }
           catch(Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }
       }
       
       /// <summary>
       /// Inserts new event in the database
       /// </summary>
       /// <param name="eventNew"></param>
       /// <returns>string</returns>
       public string InsertEvent(Event eventNew)
       {
            var eventId = "";
            var conn = connString.GetConnection();
            var comm = new SqlCommand("InsertEvent", conn) {CommandType = System.Data.CommandType.StoredProcedure};
            comm.Parameters.AddWithValue("@EventName", eventNew.EventName);
            comm.Parameters.AddWithValue("@StartingFrom", eventNew.StartingFrom);
            comm.Parameters.AddWithValue("@EndingAt", eventNew.EndingAt);
            comm.Parameters.AddWithValue("@Location", eventNew.Location);
            comm.Parameters.AddWithValue("@Latitude", eventNew.Latitude.ToString());
            comm.Parameters.AddWithValue("@Longitude", eventNew.Longitude.ToString());
            try
            {
                conn.Open();
                eventId = comm.ExecuteScalar().ToString();
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            finally
            {
                conn.Close();
            }
           return eventId;
       }

       /// <summary>
       /// Makes the connection between timeslot track and session for an event
       /// </summary>
       /// <param name="sessionId"></param>
       /// <param name="timeSlotId"></param>
       /// <param name="trackId"></param>
       public void InsertSessionInTimeSlotInTrack(Guid sessionId, Guid timeSlotId, Guid trackId)
       {
           var conn = connString.GetConnection();
           var comm = new SqlCommand("InsertSessionTimeSlotTrack", conn)
                          {CommandType = System.Data.CommandType.StoredProcedure};
           comm.Parameters.AddWithValue("@SessionID", sessionId);
           comm.Parameters.AddWithValue("@TimeSlotID", timeSlotId);
           comm.Parameters.AddWithValue("@TrackID", trackId);
           try
           {
               conn.Open();
               comm.ExecuteNonQuery();
           }
           catch (Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }

       }

       /// <summary>
       /// Sets the event with id passed in parametars as current
       /// </summary>
       /// <param name="eventId"></param>
       public void SetEventToCurrent(Guid eventId)
       {
           var conn = connString.GetConnection();
           var comm = new SqlCommand("MakeCurrent", conn) { CommandType = System.Data.CommandType.StoredProcedure };
           comm.Parameters.AddWithValue("@id", eventId);
           try
           {
               conn.Open();
               comm.ExecuteNonQuery();
           }
           catch (Exception ex)
           {
                
               log.Error(ex);
               throw;
           }
           finally
           {
               conn.Close();
           }
       }
    }
}
